from threading import Thread
from urllib import parse, request
import queue
import public
import time
import random
import logging
from datetime import datetime
from dbpool import Mysql


obtain_log = logging.getLogger('obtain')
mysql_obt = Mysql()
info_channel_id=[]
null=""
page_time=120

class refresh_time(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.time_list = public.fast_datetime

    def run(self):
        while True:
            global page_time
            current_time = int(time.strftime('%H', time.localtime(time.time())))
            if current_time in self.time_list:
                page_time = 1800
                time.sleep(page_time-5)
            elif current_time < self.time_list[0] - 1 or current_time > self.time_list[-1] + 1:
                page_time = -1
                time.sleep(60)
            else:
                page_time = 3600
                time.sleep(page_time-5)

class Info_channel(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.url = public.info_channel_url
        self.postdata = public.info_channel_post

    def run(self):
        while True:
            try:
                global info_channel_id
                req = request.Request(self.url, self.postdata)
                # req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                uopen = request.urlopen(req)
                return_data = eval(uopen.read())
                info_channel_id = [x["channel_id"] for x in return_data["result"]]
                uopen.close()
                time.sleep(60)
            except BaseException as b:
                obtain_log.error(b)
                time.sleep(60)

class Info_page(Thread):
    def __init__(self, Info_start):
        Thread.__init__(self)
        self.url = public.info_page_url
        self.size=public.info_page_size
        self.index=public.info_page_index
        self.regionId = public.info_page_regionId
        self.Info_start = Info_start

    def run(self):
        while True:
            try:
                status=True
                while status:
                    if info_channel_id != []:
                        status=False
                        time.sleep(0.5)
                all_id_list = self.initiating(info_channel_id)
                self.Info_start.push_rule(all_id_list, page_time)
                _log_str = "数据开始发送，等待" +  str(page_time) + "秒后发起下轮数据"
                obtain_log.info(_log_str)
                print(_log_str)
                while page_time == -1:
                    time.sleep(60)
                time.sleep(page_time)
            except BaseException as b:
                obtain_log.error(b)

    def Hour_sync(self):
        info_type_id = public.type_id
        info_channel_list = public.channel_list
        info_refresh_rate = public.refresh_rate
        _sql_channel = """
            SELECT
                id,
                (
                    SELECT
                        e.channel_name
                    FROM
                        e_info_channel d
                    LEFT JOIN e_info_channel_book e ON e.channel_id = d.channel_id
                    WHERE
                        d.info_id = id
                ) AS cchannel_name,
                type_id,
                py_click_rate,
                py_click_limit,
                modifyDate
            FROM
                e_info
            WHERE
                DATE_SUB(now(), INTERVAL 36 HOUR) < modifyDate
        """
        try:
            sel_channel_data = mysql_obt.getAll(_sql_channel)
            now_date = datetime.now()
            for i in sel_channel_data:
                if i[4] == 0 or i[4] == None:
                    limit_data = random.randint(300, 600)
                    if i[2] == info_type_id:
                        _push_num = random.randint(info_refresh_rate[0][0], info_refresh_rate[0][1])
                    elif i[1] in info_channel_list:
                        _push_num = random.randint(info_refresh_rate[1][0], info_refresh_rate[1][1])
                    else:
                        _push_num = random.randint(info_refresh_rate[2][0], info_refresh_rate[2][1])
                    diffdate = now_date - i[5]
                    click_rate = (diffdate.seconds // 3600 + diffdate.days * 24) * _push_num
                    if limit_data < click_rate:
                        click_rate = limit_data
                    if i[3] == None:
                        _sql_up = """UPDATE e_info SET py_click_rate = %d, click_rate = click_rate + %d, py_click_limit = %d WHERE id = %d""" % (click_rate, click_rate, limit_data, i[0])
                    else:
                        _sql_up = """UPDATE e_info SET py_click_rate = py_click_rate + %d, click_rate = click_rate + %d, py_click_limit = %d WHERE id = %d""" % (click_rate, click_rate, limit_data, i[0])
                    print(i[5].strftime("%Y%m%d"), '----->', (now_date - i[5]).seconds // 3600)
                    print(_sql_up)
                    mysql_obt.updateOne(_sql_up)
                else:
                    if i[2] == info_type_id:
                        _push_num = random.randint(info_refresh_rate[0][0], info_refresh_rate[0][1])
                    elif i[1] in info_channel_list:
                        _push_num = random.randint(info_refresh_rate[1][0], info_refresh_rate[1][1])
                    else:
                        _push_num = random.randint(info_refresh_rate[2][0], info_refresh_rate[2][1])
                    diffdate = now_date - i[5]
                    click_rate = (diffdate.seconds // 3600 + diffdate.days * 24) * _push_num
                    if i[4] < click_rate:
                        click_rate = i[4]
                    if i[3] == None:
                        _sql_up = """UPDATE e_info SET py_click_rate =%d, click_rate = click_rate + %d WHERE id = %d""" % (click_rate, click_rate, i[0])
                    else:
                        _sql_up = """UPDATE e_info SET py_click_rate = py_click_rate + %d, click_rate = click_rate + %d WHERE id = %d""" % (click_rate, click_rate, i[0])
                    print(i[5], '----->', (diffdate.seconds // 3600 + diffdate.days * 24))
                    print(_sql_up)
                    mysql_obt.updateOne(_sql_up)
        except BaseException as b:
            _log_str = "Hour_sync 函数异常：" + str(b)
            print(_log_str)

    def ops_limit(self,id):
        try:
            # _sql_sel = "SELECT py_click_rate, py_click_limit from e_info where id=%s" % id
            _sql_sel = """
                SELECT
                    (
                        SELECT
                            e.channel_name
                        FROM
                            e_info_channel d
                        LEFT JOIN e_info_channel_book e ON e.channel_id = d.channel_id
                        WHERE
                            d.info_id = id
                        LIMIT 1
                    ) AS channel_name,
                    type_id,
                    py_click_rate,
                    py_click_limit
                FROM
                    e_info
                WHERE
                    id = %s""" % id
            sel_data = mysql_obt.getAll(_sql_sel)
            id_list_one = []
            if sel_data[0][3] == 0 or sel_data[0][3] == None:
                limit_data = random.randint(300, 600)
                _sql_inc = "UPDATE e_info set py_click_limit = %d,py_click_rate=0 WHERE id=%d" %(limit_data, id)
                mysql_obt.updateOne(_sql_inc)
                id_list_one = [id, sel_data[0][0], sel_data[0][1]]
            else:
                try:
                    if sel_data[0][3] < sel_data[0][2]:
                        id_list_one = []
                    else:
                        id_list_one = [id, sel_data[0][0], sel_data[0][1]]
                except:
                    if sel_data[0][2] == None:
                        _sql_py_click_rate = "UPDATE e_info set py_click_rate = 0 WHERE id=%d" %(id)
                        mysql_obt.updateOne(_sql_py_click_rate)
                    id_list_one = [id, sel_data[0][0], sel_data[0][1]]
            return id_list_one
        except BaseException as b:
            _log_str = "ops_limit 函数异常：" + str(b)
            print(_log_str)
            obtain_log.error(_log_str)

    def initiating(self,info_channel_id):
        try:
            id_list=[]
            clickRate=[]
            for i in info_channel_id:
                if i == 0:
                    postdata = parse.urlencode({
                        "regionId": self.regionId,
                        "pageSize": self.size,
                        "pageIndex": self.index,
                    }).encode('utf-8')
                else:
                    postdata = parse.urlencode({
                        "regionId": self.regionId,
                        "channelId": i,
                        "pageSize": self.size,
                        "pageIndex": self.index,
                    }).encode('utf-8')
                req = request.Request(self.url, postdata)
                uopen = request.urlopen(req)
                return_data = eval(uopen.read())
                for x in return_data["result"]:
                    _data = self.ops_limit(x["id"])
                    if _data != []:
                        id_list.append(_data)
                    else:
                        pass
                        # print("无需添加")
                    # if x["id"] not in id_list and _status:
                    #     id_list.append(x["id"])
                    #     clickRate.append(x["clickRate"])
                uopen.close()
            print(id_list)
            obtain_log.info("ID及点击率----------------->")
            obtain_log.info(id_list)
            # obtain_log.info(clickRate)
            obtain_log.info("-------------------------->")
            return id_list
        except BaseException as b:
            obtain_log.error(b)




if __name__ == '__main__':
    # a = Info_channel()
    # print('启动线程')
    # a.start()

    b = Info_page()
    print('启动线程2')
    b.start()